package cn.laixueit.export.service;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.laixueit.export.entity.SoftExcel;
import cn.laixueit.pojo.Soft;
import cn.laixueit.service.SoftService;
import cn.laixueit.vo.SoftVo;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author duxiang
 * @date 2023/11/29 17:22
 */
@Service
public class SoftExcelService {

    @Resource
    private SoftService softService;

    public void downLoadSoftList(SoftVo softVo, HttpServletResponse response){

        List<Soft> softList = softService.list(softService.lambdaQuery().getWrapper());

        ArrayList<SoftExcel> softExcels = new ArrayList<>();

        for (Soft soft : softList) {
            SoftExcel softExcel = new SoftExcel();
            BeanUtil.copyProperties(soft,softExcel);
            softExcels.add(softExcel);
        }
        List<Map<String, Object>> sheetListMap = new ArrayList<>();
        HashMap<String, Object> map = new HashMap<>();
        ExportParams params = new ExportParams();
//        params.setTitle("免费用户只可导出部分数据");
        params.setSheetName("软件列表");
        map.put("title",params);
        map.put("entity",SoftExcel.class);
        map.put("data",softExcels);

        sheetListMap.add(map);

        try {
            Workbook workbook = ExcelExportUtil.exportExcel(sheetListMap, ExcelType.HSSF);
            ServletOutputStream out = null;
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            String finalName = URLEncoder.encode("软件列表", "UTF-8") + "_" + DateUtil.today();
            response.setHeader("Content-disposition", "attachment;filename=" + finalName + ".xlsx");
            out = response.getOutputStream();

            workbook.write(out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
